package com.yyfax.pay.quartz.adapter.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yyfax.pay.common.annotation.QueryTaskType;
import com.yyfax.pay.common.enums.PayRspCodeEnum;
import com.yyfax.pay.common.enums.PayStepEnum;
import com.yyfax.pay.common.enums.QueryTaskTypeEnum;
import com.yyfax.pay.common.enums.QueryTypeEnum;
import com.yyfax.pay.order.model.po.PayOrderLogPO;
import com.yyfax.pay.order.model.po.QueryTaskPO;
import com.yyfax.pay.order.model.vo.PayOrderVO;
import com.yyfax.pay.order.service.PayService;
import com.yyfax.pay.quartz.adapter.QueryHandlerAdapter;
import com.yyfax.pay.quartz.model.vo.TaskResultVO;

/**
 * 支付查询处理器
 * 
 * @author buyi
 * @date 2017-05-13 17:21:30
 * @since v1.0.0
 */
@Service("payQueryHandler")
@QueryTaskType(QueryTaskTypeEnum.PAY)
public class PayQueryHandler implements QueryHandlerAdapter {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private PayService payService;

	@Override
	public TaskResultVO handle(QueryTaskPO task) throws Exception {
		logger.info("执行支付查询Id:{}", task.getId());

		TaskResultVO result = new TaskResultVO(false);

		PayOrderVO payOrderVO = payService.queryPayOrder(task.getOrderId(), task.getMerchantCode(), QueryTypeEnum.AUTO);

		PayOrderLogPO queryStep = payOrderVO.getStepLast(PayStepEnum.STEP3_QUERY_RESULT);
		if (queryStep != null) { // 如果存在主动查询步骤
			// 如果主动查询状态为：成功、失败、订单不存在，则关闭主动查询任务
			if (PayRspCodeEnum.SUCCESS.isValue(queryStep.getResultCode()) || PayRspCodeEnum.PAY_CODE_PAY_FAIL.isValue(queryStep.getResultCode())
					|| PayRspCodeEnum.PAY_CODE_ORDER_NOT_FOUND.isValue(queryStep.getResultCode())) {
				result.setClose(true);
				result.setResultCode(queryStep.getResultCode());
				result.setResultMsg(queryStep.getResultMsg());
				return result;
			}
		}

		PayOrderLogPO resultStep = payOrderVO.getStepLast(PayStepEnum.STEP4_PAY_RESULT);
		if (resultStep != null) { // 如果存在结果异步回调步骤
			// 如果异步回调约定状态只有：成功、失败
			result.setClose(true);
			result.setResultCode(resultStep.getResultCode());
			result.setResultMsg(resultStep.getResultMsg());
			return result;
		}

		return null;
	}

}
